home *** CD-ROM | disk | FTP | other *** search
- Path: cnn.exu.ericsson.se!news
- From: ebumow@ebu.ericsson.com (Mickey Williams 66753)
- Newsgroups: comp.lang.c++
- Subject: Re: How to handle error in constructor
- Date: 31 Jan 1996 16:51:50 GMT
- Organization: Ericsson Inc.
- Distribution: world
- Message-ID: <4eo6n6$rbp@cnn.exu.ericsson.se>
- References: <DLyyIM.5EG@teslab.lab.oz.au>
- Reply-To: ebumow@ebu.ericsson.com
- NNTP-Posting-Host: franklin.ebu.ericsson.se
-
- In article 5EG@teslab.lab.oz.au, andrew@teslab.lab.oz.au (Andrew Phillips) writes:
- >I'm converting and enhancing a simple program in C to C++. Without going
- >into too much detail I have a class that represents a file on disk. The
- >contructor opens the file, but what should it do if the file cannot be
- >opened? The C program just calls fopen() tests the return value and
- >if there's an error it prints a message and exits.
-
- >In C++ I thought to set a flag in the constructor and have a member function
- >that tests the flag to see if the file was opened correctly.
-
- In practice, it is impossible to ensure that this works as intended. Also,
- every user of this class must understand this error handling mechanism. On
- the other hand, exceptions are part of the standard, so throwing one of
- the standard exceptions should be much safer.
-
- > This seems
- >rather inelegant -- I guess exceptions would be the elegant way but seem
- >like overkill for such a simple program.
-
- Elegant, schmelegant. It's the correct tool for the job.
-
- class CMyFile {
- //insert useful code here
- };
-
- main()
- {
- try
- {
- CMyFile theFile( "filename" );
-
- // remaining work
-
- }
- catch( /*pick an exception type*/ )
- {
- cout << "Your message here" << endl;
- }
- }
-
- > I've looked in several C++ books but
- >error handling is given scant coverage except for exception handling.
-
- That's because exception handling is the way to handle errors using
- C++ nowadays.
-
- ------
- Mickey Williams
- Author of: - Essential Visual C++ 4
- - Develop a Professional Visual C++ Application in 21 Days
-
-
-